package com.typy.www.tpay.ui.acitivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.typy.www.tpay.R;
import com.typy.www.tpay.base.BaseBackActivity;
import com.typy.www.tpay.bean.bean.BaseReturn;
import com.typy.www.tpay.bean.bean.HomeBtnBean;
import com.typy.www.tpay.bean.listvm.BuyListVm;
import com.typy.www.tpay.bean.vm.BuyVm;
import com.typy.www.tpay.bean.vm.LineVm;
import com.typy.www.tpay.bean.vm.MyAccontVm;
import com.typy.www.tpay.bean.vm.UserInfoVm;
import com.typy.www.tpay.constance.Constance;
import com.typy.www.tpay.constance.MessageEvent;
import com.typy.www.tpay.ui.adapter.IcotypeAdapter;
import com.typy.www.tpay.ui.adapter.MineGridAdapter;
import com.typy.www.tpay.ui.prt.PtrListContent;
import com.typy.www.tpay.util.ClassHoldUtil;
import com.typy.www.tpay.util.GsonUtils;
import com.typy.www.tpay.util.Logutil;
import com.typy.www.tpay.util.MessageAction;
import com.typy.www.tpay.util.MpUtil;
import com.typy.www.tpay.util.ParamsUtil;
import com.typy.www.tpay.util.StringUtil;
import com.typy.www.tpay.util.UiHelper;
import com.typy.www.tpay.util.UpdataUiUtil;
import com.typy.www.tpay.util.listviewanimations.IntentUtil;
import com.typy.www.tpay.volley.HTTPUtils;
import com.typy.www.tpay.volley.VolleyListener;
import com.zhy.android.percent.support.PercentLinearLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by 13799 on 2018/7/11.
 */

public class DigitalAssetsDetailActivity extends BaseBackActivity implements View.OnClickListener {


    private final int lineFen = 0;
    private final int lineHour = 1;
    private final int lineDay = 2;
    @BindView(R.id.ll_root)
    LinearLayout llRoot;
    TextView tvFenzhong;
    TextView tvXiaoshi;
    TextView tvRixian;
    private MineGridAdapter adapter;
    private PtrListContent ptrListContent;
    private IcotypeAdapter icotypeAdapter;
    private ListView mListVm;
    private List<BuyVm> buydatas = new ArrayList<>();
    private List<HomeBtnBean> mHomeList = new ArrayList<>();
    private ViewHolder holder;
    private String fdSeqNo;
    private TextView tvBuy, tvSell;
    private boolean mIsBuy = true;
    UserInfoVm userInfoVm;
    private String price;
    private String startPrice;
    private String endPrice;
    private String name;
    private String fdId;
    private LineChart mChart;
    int lineType = 0;
    private View emptyView;
    private List<Float> yLine = new ArrayList<>();
    private List<String> xLine = new ArrayList<>();

    public static void show(Context context, String name, String fdSeqNo, String startPrice, String endPrice, String price, String fdId) {
        Intent intent = new Intent();
        intent.putExtra("name", name);
        intent.putExtra("fdSeqNo", fdSeqNo);
        intent.putExtra("startPrice", startPrice);
        intent.putExtra("endPrice", endPrice);
        intent.putExtra("price", price);
        intent.putExtra("fdId", fdId);
        IntentUtil.intent2Activity(context, intent, DigitalAssetsDetailActivity.class);
    }

    @Override
    protected void initView() {
        super.initView();
        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        fdSeqNo = getIntent().getStringExtra("fdSeqNo");
        startPrice = getIntent().getStringExtra("startPrice");
        endPrice = getIntent().getStringExtra("endPrice");
        price = getIntent().getStringExtra("price");
        name = getIntent().getStringExtra("name");
        fdId = getIntent().getStringExtra("fdId");
        addListView();
        addView();
        initAdapter();
        refresh();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(MessageEvent msg) {
        if (msg.getKey().equals(MessageAction.FEFRESHDITAIL)) {
           refresh();
        }
    }

    private void refresh() {
        updateView();
        updateFoot(mIsBuy);
        getUserData();
        getMyaccountData();
        getlistData(1, false, mIsBuy);
        getMinLineData();
    }

    @Override
    protected int getTitleBarResId() {
        return -1;
    }

    private void addView() {
        View view1 = LayoutInflater.from(getActivity()).inflate(R.layout.item_digidetail_view1, null);
         emptyView = LayoutInflater.from(getActivity()).inflate(R.layout.activity_empty, null);
        holder = new ViewHolder(view1);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
        View foot = LayoutInflater.from(getActivity()).inflate(R.layout.foot_zpay, null);
        tvBuy = foot.findViewById(R.id.tv_buy);
        tvBuy.setOnClickListener(this);
        tvSell = foot.findViewById(R.id.tv_sell);
        tvSell.setOnClickListener(this);
        View mpView = LayoutInflater.from(getActivity()).inflate(R.layout.activity_digidetail_mp, null);
        mChart = mpView.findViewById(R.id.chart1);
        tvFenzhong = mpView.findViewById(R.id.tv_fenzhong);
        tvFenzhong.setOnClickListener(this);
        tvXiaoshi = mpView.findViewById(R.id.tv_xiaoshi);
        tvXiaoshi.setOnClickListener(this);
        tvRixian = mpView.findViewById(R.id.tv_rixian);
        tvRixian.setOnClickListener(this);
        mListVm.addHeaderView(view1);
        mListVm.addHeaderView(mpView);
        mListVm.addHeaderView(foot);
    }

    private void addListView() {
        ptrListContent = new PtrListContent(getActivity()) {
            @Override
            protected void getPage(int pageIndex, boolean refresh) {
                refresh();
            }
        };
        mListVm = ptrListContent.getListView();
        ptrListContent.hideHint();
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        llRoot.addView(ptrListContent.getmView(), params);
    }

    private void initAdapter() {
        adapter = new MineGridAdapter(getActivity());
        holder.gvFour.setAdapter(adapter);
        holder.gvFour.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Object obj = adapterView.getItemAtPosition(i);
                if (obj instanceof HomeBtnBean) {
                    switch (((HomeBtnBean) obj).getBtnName()) {
                        case "发布出售":
                            FabuActivity.show(getActivity(), ClassHoldUtil.FABUSELL, price, name);
                            break;
                        case "发布购买":
                            FabuActivity.show(getActivity(), ClassHoldUtil.FABUBUY, price, name);
                            break;
                        case "订单":
                            RecordActivity.show(getActivity(), ClassHoldUtil.DIGIDINGDANG);
                            break;
                        case "交易记录":
                            RecordActivity.show(getActivity(), ClassHoldUtil.DigiDetail, name);
                            break;
                    }
                }
            }
        });
        setList();
        icotypeAdapter = new IcotypeAdapter(getActivity());
        icotypeAdapter.setmType(ClassHoldUtil.DigiDetail);
        icotypeAdapter.setFdName(name, fdSeqNo);
        mListVm.setAdapter(icotypeAdapter);
    }


    private void setList() {
        if (mHomeList != null && mHomeList.size() == 0) {
            mHomeList.add(HomeBtnBean.getBean("发布出售", R.drawable.jiaoyi_chushoudingdan));
            mHomeList.add(HomeBtnBean.getBean("发布购买", R.drawable.jiaoyi_goumaidingdan));
            mHomeList.add(HomeBtnBean.getBean("订单", R.drawable.jiaoyi_dingdan));
            mHomeList.add(HomeBtnBean.getBean("交易记录", R.drawable.jiaoyi_jiaoyijilu));
        }
        adapter.setList(mHomeList);
        adapter.notifyDataSetChanged();
    }

    private void updateView() {
        UpdataUiUtil.getDefaul().setText(name, holder.tvTitle)
                .setText(price, holder.tvYue)
                .setText(endPrice, holder.tvFenxiangfen)
                .setText(startPrice, holder.tvJifen)
                .setText(name + "资产", holder.tvZichanTitle);
        holder.btnTitlebarLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_linear;
    }


    private void updateFoot(boolean isBuy) {
        if (isBuy) {
            tvBuy.setTextColor(getResources().getColor(R.color.text_moneyred));
            tvSell.setTextColor(getResources().getColor(R.color.text_darkcolor));
            if (mIsBuy != isBuy) {
                getlistData(1, true, isBuy);
                mIsBuy = isBuy;
            }
        } else {
            tvSell.setTextColor(getResources().getColor(R.color.text_moneyred));
            tvBuy.setTextColor(getResources().getColor(R.color.text_darkcolor));
            if (mIsBuy != isBuy) {
                getlistData(1, true, isBuy);
                mIsBuy = isBuy;
            }
        }
    }

    private void updateLine(int lineType) {
        this.lineType=lineType;
        if (lineType ==lineFen) {
            tvFenzhong.setTextColor(getResources().getColor(R.color.white));
            tvXiaoshi.setTextColor(getResources().getColor(R.color.text_darkcolor));
            tvRixian.setTextColor(getResources().getColor(R.color.text_darkcolor));
            tvFenzhong.setBackgroundColor(getResources().getColor(R.color.titlebar_bulue));
            tvXiaoshi.setBackgroundColor(getResources().getColor(R.color.white));
            tvRixian.setBackgroundColor(getResources().getColor(R.color.white));
        } else if(lineType ==lineHour) {
            tvFenzhong.setTextColor(getResources().getColor(R.color.text_darkcolor));
            tvXiaoshi.setTextColor(getResources().getColor(R.color.white));
            tvRixian.setTextColor(getResources().getColor(R.color.text_darkcolor));
            tvFenzhong.setBackgroundColor(getResources().getColor(R.color.white));
            tvXiaoshi.setBackgroundColor(getResources().getColor(R.color.titlebar_bulue));
            tvRixian.setBackgroundColor(getResources().getColor(R.color.white));
        }else{
            tvFenzhong.setTextColor(getResources().getColor(R.color.text_darkcolor));
            tvXiaoshi.setTextColor(getResources().getColor(R.color.text_darkcolor));
            tvRixian.setTextColor(getResources().getColor(R.color.white));
            tvFenzhong.setBackgroundColor(getResources().getColor(R.color.white));
            tvXiaoshi.setBackgroundColor(getResources().getColor(R.color.white));
            tvRixian.setBackgroundColor(getResources().getColor(R.color.titlebar_bulue));
        }
        getMinLineData();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_sell:
                updateFoot(false);
                break;
            case R.id.tv_buy:
                updateFoot(true);
                break;
            case R.id.tv_fenzhong:
                updateLine(lineFen);
                break;
            case R.id.tv_xiaoshi:
                updateLine(lineHour);
                break;
            case R.id.tv_rixian:
                updateLine(lineDay);
                break;
        }
    } //获取个人信息

    private void getUserData() {
        ParamsUtil params = new ParamsUtil();
        HTTPUtils.post(this, Constance.getMyselfinfoURL(), params.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {
                userInfoVm = GsonUtils.parseJSON(ret.getData().toString(), UserInfoVm.class);
                UpdataUiUtil.getDefaul().setText(userInfoVm.getFdAmount(), holder.tvYueDetail);
            }

            @Override
            public void onResponseErr(int code, String msg) {
                UiHelper.showToast(getActivity(), msg);
            }
        });
    }

    private void getMyaccountData() {
        ParamsUtil paramsUtil = new ParamsUtil();
        paramsUtil.put("fdIconTypeName", name);
        HTTPUtils.post(getActivity(), Constance.getMyaccountURL(), paramsUtil.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {
                MyAccontVm vm = GsonUtils.parseJSON(ret.getData().toString(), MyAccontVm.class);
                if (vm != null) {
                    UpdataUiUtil.getDefaul().setText(vm.getFdIconCount(), holder.tvZichan);
                }
            }

            @Override
            public void onResponseErr(int code, String msg) {
            }
        });
    }

    private void getMinLineData() {
        ParamsUtil paramsUtil = new ParamsUtil();
        paramsUtil.put("fdIconTypeName", name);
        String url = "";
        if (lineType == 0) {
            url = Constance.getMinlineURL();
        } else if (lineType == 1) {
            url = Constance.getHourlineURL();
        } else if (lineType == 2) {
            url = Constance.getDaylineURL();
        }

        HTTPUtils.post(getActivity(), url, paramsUtil.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {
                LineVm vm = GsonUtils.parseJSON(ret.getData().toString(), LineVm.class);
                if (vm != null) {
                    yLine = vm.getyLine();
                    xLine = vm.getxLine();
                    if(lineType == 2) {
                        MpUtil.initMp(mChart);
                        MpUtil.setData(getActivity(), mChart, name, xLine, yLine);
                    }else {
                        MpUtil.initMp(mChart);
                        MpUtil.setData(getActivity(), mChart, name, xLine, yLine);
                    }
                }
            }

            @Override
            public void onResponseErr(int code, String msg) {
            }
        });
    }

    private void getlistData(final int pageIndex, final boolean refresh, final boolean isbuy) {
        ParamsUtil params = new ParamsUtil();
        params.put("pageNum", pageIndex);
        params.put("pageSize", Constance.LIMT);
        String url = "";
        if (isbuy)
            url = Constance.getTobuylistURL();
        else
            url = Constance.getTosellerlistURL();
        HTTPUtils.post(getActivity(), url, params.getParams(), new VolleyListener() {
            @Override
            public void onResponse(BaseReturn ret) {
                if (refresh || pageIndex == 1)
                    buydatas.clear();
                BuyListVm vm = GsonUtils.parseJSON(ret.getData().toString(), BuyListVm.class);
                if (vm != null && vm.getData() != null) {
                    buydatas.addAll(vm.getData());
                    icotypeAdapter.setBuyData(buydatas);
                    icotypeAdapter.setIsBuy(isbuy);
                    icotypeAdapter.notifyDataSetChanged();
                    ptrListContent.loadInitialPage(mListVm.getCount(), vm.getCount());
                } else {
                    ptrListContent.loadInitialPage(0);
                }
            }

            @Override
            public void onResponseErr(int code, String msg) {
                ptrListContent.loadInitialPage(0);

            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    static class ViewHolder {
        @BindView(R.id.btn_titlebar_left)
        ImageButton btnTitlebarLeft;
        @BindView(R.id.btn_titlebar_right)
        Button btnTitlebarRight;
        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.tv_zichan_title)
        TextView tvZichanTitle;
        @BindView(R.id.tv_zichan)
        TextView tvZichan;
        @BindView(R.id.tv_yue_title)
        TextView tvYueTitle;
        @BindView(R.id.tv_yue_detail)
        TextView tvYueDetail;
        @BindView(R.id.tv_yue_titles)
        TextView tvYueTitles;
        @BindView(R.id.tv_yue)
        TextView tvYue;
        @BindView(R.id.ll_amount)
        PercentLinearLayout llAmount;
        @BindView(R.id.tv_fenxiangfen_titles)
        TextView tvFenxiangfenTitles;
        @BindView(R.id.tv_fenxiangfen)
        TextView tvFenxiangfen;
        @BindView(R.id.ll_share)
        PercentLinearLayout llShare;
        @BindView(R.id.tv_jifen_titles)
        TextView tvJifenTitles;
        @BindView(R.id.tv_jifen)
        TextView tvJifen;
        @BindView(R.id.ll_point)
        PercentLinearLayout llPoint;
        @BindView(R.id.gv_four)
        GridView gvFour;
        @BindView(R.id.ll_listhold)
        LinearLayout llListhold;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
